#ifdef VERTEX
uniform mat4 uProjMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uModelMatrix;
uniform mat4 uShadowMatrix[4];
uniform vec3 uCameraPos;
uniform vec4 uBaseColor;

layout(location = 0) in vec4 aPosition;
layout(location = 1) in vec2 aTexCoord;
layout(location = 2) in vec4 aNormal;
layout(location = 3) in vec4 aColor;

out vec3 vPosition;
out vec3 vNormal;
out vec2 vTexCoord;
out vec4 vColor;
out vec3 vViewDir;
out vec4 vShadowCoord[4];

void main()
{
	mat4 viewProj = uProjMatrix * uViewMatrix;
	vec4 position = uModelMatrix * aPosition;

	vPosition = position.xyz;
	vNormal = normalize(uModelMatrix * aNormal).xyz;
	vTexCoord = aTexCoord;
	vColor = aColor * uBaseColor;
	vViewDir = uCameraPos - position.xyz;

#ifdef ENABLE_SHADOW
	vShadowCoord[0] = uShadowMatrix[0] * position;
	vShadowCoord[1] = uShadowMatrix[1] * position;
	vShadowCoord[2] = uShadowMatrix[2] * position;
	vShadowCoord[3] = uShadowMatrix[3] * position;
#endif
	gl_Position = viewProj * position;
}
#endif

#ifdef FRAGMENT
uniform sampler2D uTexture;
uniform vec4 uLightColor;
uniform vec3 uEmissiveColor;

in vec3 vPosition;
in vec3 vNormal;
in vec2 vTexCoord;
in vec4 vColor;
in vec3 vViewDir;
in vec4 vShadowCoord[4];
out vec4 fragColor;

void main()
{
	vec4 color = texture(uTexture, vTexCoord) * vColor;

#ifndef DISABLE_ALPHATEST
	if (color.a < 0.5) discard;
#endif

#ifdef ENABLE_SHADOW
	vec4 lightDir = common_lightshadow(vPosition, vShadowCoord);
#else
	vec4 lightDir = common_light(vPosition);
#endif
	float intensity = lightDir.w;
	float dotNL = dot(vNormal, lightDir.xyz) * 0.5 + 0.5;
	vec3 viewDir = normalize(vViewDir);
	vec3 radiance = uLightColor.rgb * (dotNL * intensity * 3.14159265359);
	vec3 reflection = common_brdf(color.rgb, viewDir, vNormal, lightDir.xyz) * radiance;

#ifdef ENABLE_IBL
	reflection += common_ibl(color.rgb, viewDir, vNormal);
#endif
	color.rgb = reflection + uEmissiveColor;

#ifdef ENABLE_TONEMAPPING
	color = common_tonemapping(color);
#endif

#ifdef ENABLE_FOG
	color = common_fog(color, vViewDir);
#endif
	fragColor = color;
}
#endif